/*
 * @Date: 2022-01-11 17:28:00
 * @LastEditors: 春贰
 * @Desc: 
 * @LastEditTime: 2022-10-11 09:35:54
 * @FilePath: \web\src\core\api\websocket.js
 */
import store from "@/core/store"
import { SmileOutlined,FrownOutlined } from '@ant-design/icons-vue';
import { notification } from 'ant-design-vue';
import {  h } from 'vue'; 
export default class SocketService {
  

  static instance = null;
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService();
    }
    return this.instance;
  }
  maxRetry = 5;
  url = window.configs.servers[localStorage.getItem("serverIndex")]['websocket'];
  // 和服务端连接的socket对象
  ws = null;
  // 存储回调函数
  callBackMapping = {};
  // 标识是否连接成功
  connected = false;
  // 记录重试的次数
  sendRetryCount = 0;
  // 重新连接尝试的次数
  connectRetryCount = 0;
  //  定义连接服务器的方法
  connect() {
    // 连接服务器
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket');
    }


    //'echo-protocol'   MODE
    console.log(this.url);
    this.ws = new WebSocket(this.url);
    // 连接成功的事件
    this.ws.onopen = () => {
      console.log('连接服务端成功了') 
      this.send("上线了",'online')
      this.connected = true;
      // 重置重新连接的次数
      this.connectRetryCount = 0;
    };
    // 1.连接服务端失败
    // 2.当连接成功之后, 服务器关闭的情况
    this.ws.onclose = () => {
      console.log('连接服务端失败');
      this.connected = false; 
      this.connectRetryCount++;
      if (this.connectRetryCount < this.maxRetry) {
        setTimeout(() => {
          this.connect();
        }, 500 * this.connectRetryCount);
      }
    };
    // 得到服务端发送过来的数据
    this.ws.onmessage = msg => {      

      if (!localStorage.getItem("USER_INFO")) {
        notification.open({
          message:   '缓存异常', 
          icon: () => h(FrownOutlined, { style: 'color: #cccccc' }),
        });
        store.dispatch("user/logout")  
        return;
      }
      
      let response = JSON.parse(msg.data);
      let type = response.type||"";
      console.log( '从服务端获取到了数据',response);  
      
      switch (type) {
        case 'online': 
          store.commit('user/SET_ONLINE_USER',  response.user_list);  

          if (JSON.parse(localStorage.getItem("USER_INFO")).id!=response.userinfo.id && response.userinfo.user_name) {
            notification.open({
              message: response.userinfo.user_name +  '上线了!', 
              icon: () => h(SmileOutlined, { style: 'color: #108ee9' }),
            });
          } 


          break;

          case 'offline': 
          store.commit('user/SET_ONLINE_USER',  response.user_list);  

          if (JSON.parse(localStorage.getItem("USER_INFO")).id!=response.userinfo.id && response.userinfo.user_name) {
            notification.open({
              message: response.userinfo.user_name +  '下线了!', 
              icon: () => h(FrownOutlined, { style: 'color: #cccccc' }),
            });
          } 
 
          break;

          case 'kick': 
          notification.open({
            message:   '强制下线了', 
            icon: () => h(FrownOutlined, { style: 'color: #cccccc' }),
          });
          store.dispatch("user/logout")  
          break;
         
      
        default:
          console.log(response, '从服务端获取到了数据'+type);
          break;
      }
     
      
    };
    this.ws.onerror = msg => {
      console.log(msg, 'error');
    };

  }

  // 发送数据的方法
  send(content,type) {
    const senddata = {
      token: localStorage.getItem("USER_TOKEN"),
      userinfo: JSON.parse(localStorage.getItem("USER_INFO")) ,
      content: content,
      type:type
    }

     console.log("客户端发送：",senddata);

    // 判断此时此刻有没有连接成功
    if (this.connected) {
      this.sendRetryCount = 0;
      try {
        this.ws.send(JSON.stringify(senddata));
      } catch (e) {
        this.ws.send(senddata);
      }
    } else {
      this.sendRetryCount++;
      if (this.sendRetryCount < this.maxRetry) { 
        setTimeout(() => {
          this.send(content,type);
        }, this.sendRetryCount * 500);
      }

    }
  }
}
